<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="炼丹手记, python,machine learning,deep learning,html,css,c,c++,cpp,cmake,ros,linux,ubuntu">
    <meta name="description" content="本文记录了我炼丹的心得">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>炼丹手记 | JackWang&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 5.4.2">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size: 100% 100%;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">JackWang&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-book-reader" style="zoom: 0.6;"></i>
      
      <span>博客</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按标签归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按目录归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按日期分类文章</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>



<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">JackWang&#39;s Blog</div>
        <div class="logo-desc">
            
            JackWang的个人博客
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book-reader"></i>
			
			博客
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
                              <span>按标签归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
                              <span>按目录归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
                              <span>按日期分类文章</    span>

                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('抱歉，这篇文章并不想让所有人都看到，请输入授权密码观看')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220202001104734.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">炼丹手记</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Python/">
                                <span class="chip bg-color">Python</span>
                            </a>
                        
                            <a href="/tags/Deep-Learning/">
                                <span class="chip bg-color">Deep Learning</span>
                            </a>
                        
                            <a href="/tags/Pytorch/">
                                <span class="chip bg-color">Pytorch</span>
                            </a>
                        
                            <a href="/tags/AI/">
                                <span class="chip bg-color">AI</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Deep-Learning-Blogs/" class="post-category">
                                Deep Learning Blogs
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-02-02
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-06-01
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    15 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>本文是我在炼丹的过程中的一些心得</p>
</blockquote>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220202001104734.png" alt="Pytorch官网"></p>
<h1 id="炼丹手记"><a href="#炼丹手记" class="headerlink" title="炼丹手记"></a>炼丹手记</h1><p>因为目前是一个本科生，所以经常需要balance课程、科研、竞赛、写代码……所以一个问题就是我经常一段时间忙于做事情A，一段时间忙于做事情B。</p>
<p>这个对于炼丹其实是不太好的，因为炼丹的经验会随着时间的流逝而遗忘，因此决定还是把自己的炼丹时候的心得都记录下来，这样的话方便以后回顾、总结、提高。</p>
<p>此外，因为我用的是Pytorch，所以有一些关于Pytorch的心得，这部分工具的心得可能不是很适合TensorFlow用户，因此略掉就好。</p>
<h2 id="1-Pytorch读取Numpy"><a href="#1-Pytorch读取Numpy" class="headerlink" title="1. Pytorch读取Numpy"></a>1. Pytorch读取Numpy</h2><p>有的时候数据是以numpy的npy或者npz形式保存的，这个时候直接使用<code>np.load</code>就可以读取了。可是读取完了之后从numpy的ndarray转成torch的tensor的时候会有问题。</p>
<p>具体来说就是首先是数据类型的问题：</p>
<ul>
<li>numpy里转数据类型不如pytorch方便</li>
<li>pytorch有的时候在计算的时候是需要统一数据类型为float的，因此用numpy转换数据类型和用torch转换数据类型混着来容易分不清楚</li>
<li>有的时候pytorch计算有需要LongTensor，例如用交叉熵/负对数似然损失函数，因为去nature log的时候数值的范围比较大</li>
</ul>
<p><strong>因此，如果数据是numpy的文件的话，读完了之后直接转torch的tensor再进行后续操作</strong></p>
<p>读的时候<code>np.load</code>，而<code>torch.from_numpy</code>会直接帮我们完成从<code>np.ndarrary</code>到<code>torch.Tensor</code>的转换，转换过程中保持数据格式、内存对齐等属性不变，然后我们再用<code>torch.Tensor.long()</code>之类的方法转换</p>
<p>例如：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">ExampleDataset</span><span class="token punctuation">(</span>Dataset<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        data <span class="token operator">=</span> torch<span class="token punctuation">.</span>from_numpy<span class="token punctuation">(</span>np<span class="token punctuation">.</span>load<span class="token punctuation">(</span>file_path<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>float<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 类似的，还可以是</span>
        long <span class="token operator">=</span> torch<span class="token punctuation">.</span>from_numpy<span class="token punctuation">(</span>np<span class="token punctuation">.</span>load<span class="token punctuation">(</span>file_path<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>long<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="2-Pytorch使用CrossEntropy"><a href="#2-Pytorch使用CrossEntropy" class="headerlink" title="2. Pytorch使用CrossEntropy"></a>2. Pytorch使用CrossEntropy</h2><p>CrossEntropy损失函数一般用于分类任务。具体的原理就是交叉熵（Cross-Entropy）其实等价于最大化似然（Maximize Likelihood），或者说最小化对数负似然（Negative Log Likelihood），即让网络输出的分布和真实的数据的分布越相似越好。因此，交叉熵损失（Cross-Entropy Loss）其实等于负对数似然（NLL Loss）</p>
<p>在Pytorch中，提供了负对数似然损失函数的API，然后在其基础上又集成了softmax，就成了Pytorch中的Cross-Entropy损失函数。因此一般在分类的时候都是直接使用Cross-Entropy作为损失函数的，就避免了我们自己写softmax。</p>
<h3 id="1-数据类型的问题"><a href="#1-数据类型的问题" class="headerlink" title="1. 数据类型的问题"></a>1. 数据类型的问题</h3><p>但是使用Cross-Entropy的时候因为要计算Softmax，所以Pytorch要求输入的<code>target</code>是long类型的，即输入的label要求是long，输入的<code>input</code>也就是预测值是float</p>
<p>所以最好在读取完数据之后把<code>target</code>，也就是y转为long，y_pred转为float，即</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># train</span>
self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>train<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>train_loader<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 注意在这里转换，如果Dataset里面以及转换了这里就不要转换了</span>
    x<span class="token punctuation">,</span> y <span class="token operator">=</span> x<span class="token punctuation">.</span>to<span class="token punctuation">(</span>dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">,</span> device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>to<span class="token punctuation">(</span>
        device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># zero grad</span>
    self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>zero_grad<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># calculate loss</span>
    output <span class="token operator">=</span> self<span class="token punctuation">.</span>network<span class="token punctuation">(</span>x<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 注意这里要转成float和long</span>
    loss<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor <span class="token operator">=</span> self<span class="token punctuation">.</span>loss_function<span class="token punctuation">(</span>output<span class="token punctuation">.</span>float<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>long<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># Gradient Descent</span>
    loss<span class="token punctuation">.</span>backward<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># Step</span>
    self<span class="token punctuation">.</span>optimizer<span class="token punctuation">.</span>step<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>否则会出现如下的报错</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220317100142950.png" alt="没有转成long的错误"></p>
<h3 id="2-输入顺序问题"><a href="#2-输入顺序问题" class="headerlink" title="2. 输入顺序问题"></a>2. 输入顺序问题</h3><p>此外，除了要求转成long，计算CrossEntropyLoss的时候是要求预测值作为第一个实参，真实的label作为第二个实参，即</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># train</span>
self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>train<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>train_loader<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 注意在这里转换，如果Dataset里面以及转换了这里就不要转换了</span>
    x<span class="token punctuation">,</span> y <span class="token operator">=</span> x<span class="token punctuation">.</span>to<span class="token punctuation">(</span>dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">,</span> device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>to<span class="token punctuation">(</span>
        device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># zero grad</span>
    self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>zero_grad<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># calculate loss</span>
    output <span class="token operator">=</span> self<span class="token punctuation">.</span>network<span class="token punctuation">(</span>x<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 注意第一位是预测值，第二位是long的label</span>
    loss<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor <span class="token operator">=</span> self<span class="token punctuation">.</span>loss_function<span class="token punctuation">(</span>output<span class="token punctuation">,</span> y<span class="token punctuation">.</span>long<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># Gradient Descent</span>
    loss<span class="token punctuation">.</span>backward<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># Step</span>
    self<span class="token punctuation">.</span>optimizer<span class="token punctuation">.</span>step<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>否则就会出现下面的错误</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220317100515724.png" alt="顺序出错的报错"></p>
<h3 id="3-输入维度的问题"><a href="#3-输入维度的问题" class="headerlink" title="3. 输入维度的问题"></a>3. 输入维度的问题</h3><p>对于分类问题来说，我们输入的$x$最后得到的$y_{pred}$是$[Batch, Class]$类型的数据，因此Pytoch的CrossEntropyLoss要求输入的预测值的是二维的数据。但是Pytorch却要求GroundTruth的$y$的形状是一维的，长度和$Batch$数相等，每一位表示对应的类别，即</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># train</span>
self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>train<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>train_loader<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 注意在这里转换，如果Dataset里面以及转换了这里就不要转换了</span>
    x<span class="token punctuation">,</span> y <span class="token operator">=</span> x<span class="token punctuation">.</span>to<span class="token punctuation">(</span>dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">,</span> device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>to<span class="token punctuation">(</span>
        device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># zero grad</span>
    self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>zero_grad<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># calculate loss</span>
    output <span class="token operator">=</span> self<span class="token punctuation">.</span>network<span class="token punctuation">(</span>x<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 注意对ground truth进行了squeeze来保证是一维的，因为dataloader里面进行了stack</span>
    loss<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor <span class="token operator">=</span> self<span class="token punctuation">.</span>loss_function<span class="token punctuation">(</span>output<span class="token punctuation">,</span> y<span class="token punctuation">.</span>squeeze<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>long<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># Gradient Descent</span>
    loss<span class="token punctuation">.</span>backward<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># Step</span>
    self<span class="token punctuation">.</span>optimizer<span class="token punctuation">.</span>step<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>否则会报错    </p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220317101634866.png" alt="形状出错的报错"></p>
<h2 id="3-训练代码调bug"><a href="#3-训练代码调bug" class="headerlink" title="3. 训练代码调bug"></a>3. 训练代码调bug</h2><p>把所有的测试代码写完了之后一般来说是没法直接开始训练的，需要调一下bug，但是这个时候因为<code>epoch</code>、<code>dataloader</code>的循环都写好了，因此如果直接调试的话可能会卡到训练部分。</p>
<p>这个时候可以给训练循环的这类步骤直接break掉就行了，因为的目的在于验证流程，即验证是否可以跑完流程而非开始训练，因此这个时候break掉即可。即</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">for</span> epoch <span class="token keyword">in</span> range<span class="token punctuation">(</span>n_epoch<span class="token punctuation">)</span><span class="token punctuation">:</span>
    x<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor
    y<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor

    <span class="token comment" spellcheck="true"># train</span>
    self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>train<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> tqdm<span class="token punctuation">(</span>enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>train_loader<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        x<span class="token punctuation">,</span> y <span class="token operator">=</span> x<span class="token punctuation">.</span>to<span class="token punctuation">(</span>dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">,</span> device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>to<span class="token punctuation">(</span>
            device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># zero grad</span>
        self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>zero_grad<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># calculate loss</span>
        output <span class="token operator">=</span> self<span class="token punctuation">.</span>network<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        loss<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor <span class="token operator">=</span> self<span class="token punctuation">.</span>loss_function<span class="token punctuation">(</span>output<span class="token punctuation">,</span> y<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># Gradient Descent</span>
        loss<span class="token punctuation">.</span>backward<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># Step</span>
        self<span class="token punctuation">.</span>optimizer<span class="token punctuation">.</span>step<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># summary in train</span>
        self<span class="token punctuation">.</span>writer<span class="token punctuation">.</span>add_scalar<span class="token punctuation">(</span>tag<span class="token operator">=</span><span class="token string">"loss/train"</span><span class="token punctuation">,</span> scalar_value<span class="token operator">=</span>loss<span class="token punctuation">.</span>item<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                               global_step<span class="token operator">=</span>epoch <span class="token operator">*</span> len<span class="token punctuation">(</span>self<span class="token punctuation">.</span>train_loader<span class="token punctuation">)</span> <span class="token operator">+</span> step<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 注意，调试的时候break即可</span>
        <span class="token keyword">break</span>

    <span class="token comment" spellcheck="true"># validation</span>
    self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>eval<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">with</span> torch<span class="token punctuation">.</span>no_grad<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> tqdm<span class="token punctuation">(</span>enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>val_loader<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            x<span class="token punctuation">,</span> y <span class="token operator">=</span> x<span class="token punctuation">.</span>to<span class="token punctuation">(</span>dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">,</span> device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>to<span class="token punctuation">(</span>
                device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">)</span>
            <span class="token comment" spellcheck="true"># calculate loss</span>
            output <span class="token operator">=</span> self<span class="token punctuation">.</span>network<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
            loss <span class="token operator">=</span> self<span class="token punctuation">.</span>loss_function<span class="token punctuation">(</span>output<span class="token punctuation">,</span> y<span class="token punctuation">)</span>
            <span class="token comment" spellcheck="true"># summary in validation</span>
            self<span class="token punctuation">.</span>writer<span class="token punctuation">.</span>add_scalar<span class="token punctuation">(</span>tag<span class="token operator">=</span><span class="token string">"loss/test"</span><span class="token punctuation">,</span> scalar_value<span class="token operator">=</span>loss<span class="token punctuation">.</span>item<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                                           global_step<span class="token operator">=</span>epoch <span class="token operator">*</span> len<span class="token punctuation">(</span>self<span class="token punctuation">.</span>val_loader<span class="token punctuation">)</span> <span class="token operator">+</span> step<span class="token punctuation">)</span>


            <span class="token comment" spellcheck="true">#同上，调试的时候break掉</span>
            <span class="token keyword">break</span>

    <span class="token comment" spellcheck="true"># early stop</span>
    <span class="token keyword">if</span> loss <span class="token operator">&lt;</span> min_val_loss<span class="token punctuation">:</span>
        min_val_loss <span class="token operator">=</span> loss
        earl_stop <span class="token operator">=</span> <span class="token number">0</span>
        self<span class="token punctuation">.</span>save_check_point<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        earl_stop <span class="token operator">+=</span> <span class="token number">1</span>

    <span class="token keyword">if</span> earl_stop <span class="token operator">></span> self<span class="token punctuation">.</span>early_stop_cnt<span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">"{Fore.YELLOW}Early Stoped at epoch: {epoch}"</span><span class="token punctuation">)</span>
        <span class="token keyword">break</span>

    <span class="token comment" spellcheck="true"># print logs</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">"Epoch: {Fore.GREEN + Style.BRIGHT}{epoch}/{n_epoch}{Style.RESET_ALL}, "</span>
        <span class="token string">"val_loss: {Fore.GREEN + Style.BRIGHT}{loss:>.5f}{Style.RESET_ALL}, "</span>
        <span class="token string">"min_val_loss: {Fore.GREEN + Style.BRIGHT}{min_val_loss:>.5f}{Style.RESET_ALL}"</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="4-训练阶段Early-Stop"><a href="#4-训练阶段Early-Stop" class="headerlink" title="4. 训练阶段Early Stop"></a>4. 训练阶段Early Stop</h2><p>在训练网络的过程中，可能会出现过拟合，因此就需要用Early Stop技术来防止过拟合。判断是否过拟合的依据是看训练和验证阶段的loss曲线，但在真实训练的时候是没办法人工一直查看损失曲线的，因此我们更希望在代码里面能够进行判断。</p>
<p>相比于记录下来每一个epoch的性能，Early Stop其实更加简单粗暴，<strong>Early Stop指的其实就是如果网络在N个epoch中性能都没有下降，那么就停止训练</strong>。</p>
<p>在代码里的实现类似这样</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">for</span> epoch <span class="token keyword">in</span> range<span class="token punctuation">(</span>n_epoch<span class="token punctuation">)</span><span class="token punctuation">:</span>
    x<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor
    y<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor

    <span class="token comment" spellcheck="true"># train</span>
    self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>train<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> tqdm<span class="token punctuation">(</span>enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>train_loader<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">pass</span>

    <span class="token comment" spellcheck="true"># validation</span>
    self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>eval<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">with</span> torch<span class="token punctuation">.</span>no_grad<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> tqdm<span class="token punctuation">(</span>enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>val_loader<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            <span class="token keyword">pass</span>

    <span class="token comment" spellcheck="true"># early stop</span>
    <span class="token keyword">if</span> loss <span class="token operator">&lt;</span> min_val_loss<span class="token punctuation">:</span>
        min_val_loss <span class="token operator">=</span> loss
        earl_stop <span class="token operator">=</span> <span class="token number">0</span>
        self<span class="token punctuation">.</span>save_check_point<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        earl_stop <span class="token operator">+=</span> <span class="token number">1</span>

    <span class="token keyword">if</span> earl_stop <span class="token operator">></span> self<span class="token punctuation">.</span>early_stop_cnt<span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">"{Fore.YELLOW}Early Stoped at epoch: {epoch}"</span><span class="token punctuation">)</span>
        <span class="token keyword">break</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="5-代码里使用SummaryWriter"><a href="#5-代码里使用SummaryWriter" class="headerlink" title="5. 代码里使用SummaryWriter"></a>5. 代码里使用SummaryWriter</h2><p>如果代码里使用了SummaryWriter，那么调试的时候有一个问题，就是Python是遇到报错之后就直接退出，不会运行完所有的代码。</p>
<p>而SummaryWriter是一个异步的服务程序，因此在使用之后是需要关闭的。如果这次调试没有关闭SummaryWriter，那么下一次调试产生的数据就会写入到这次调试的数据里去。</p>
<p>所以在调试阶段为了防止这个问题，可以吧SummaryWriter的关闭方法写入到类的<code>__del__</code>方法里去。<code>__del__</code>是在对象被销毁的时候运行，一般在程序运行结束（不管是正常结束还是因为异常报错）的时候，Python会自动销毁所有的对象。</p>
<p>因此如果我们把训练的代码写成了一个类的话，重写<code>__del__</code>方法就可以帮助我们关闭SummaryWriter</p>
<p>具体在代码中是这样的</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">NetworkTrainer</span><span class="token punctuation">:</span>
    available_device <span class="token operator">=</span> <span class="token string">"cuda:0"</span> <span class="token keyword">if</span> torch<span class="token punctuation">.</span>cuda<span class="token punctuation">.</span>is_available<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">else</span> <span class="token string">"cpu"</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>writer <span class="token operator">=</span> SummaryWriter<span class="token punctuation">(</span>log_dir<span class="token operator">=</span>path2log<span class="token punctuation">)</span>
        <span class="token keyword">pass</span>

    <span class="token keyword">def</span> <span class="token function">__del__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>writer<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="6-高效使用tqdm"><a href="#6-高效使用tqdm" class="headerlink" title="6. 高效使用tqdm"></a>6. 高效使用tqdm</h2><p>在训练代码的时候，往往使用tqdm来给出来一个训练的进度条，例如下面</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/697264-20200723170905473-1915244785.png" alt="tqdm可视化得到的训练进度条"></p>
<p>然而很多时候我们都需要再输出一些内容，比如训练和验证的loss，分类的准确率这类信息。</p>
<p>如果我们直接print的话，就会导致tqdm的进度条断开，非常的不美观，因此我们可以使用tqdm的<code>set_description</code>或者<code>set_postfix</code>方法来设置一些训练的信息，可是这样做并不优雅，因为能够显示的信息有限。一个优雅的解决方案如下面的gif所示</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/深度录屏_x-terminal-emulator_20220317111046.gif" alt="优雅的解决方案"></p>
<p>即每次输出都会保证tqdm的进度条在最下面。要实现这样的效果，其实通过tqdm的另外一个方法就行了。</p>
<p>在输出的时候，缓冲区是被tqdm占用的，因此直接输出肯定会有问题，我们使用tqdm的write方法来让tqdm自动处理即可。例如实现上面的效果的代码</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">train</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> n_epoch<span class="token punctuation">:</span> int<span class="token punctuation">,</span> early_stop<span class="token punctuation">:</span> int<span class="token punctuation">)</span><span class="token punctuation">:</span>
        x<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor
        y<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor
        max_acc <span class="token operator">=</span> <span class="token number">0</span>
        early_stop_cnt <span class="token operator">=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> epoch <span class="token keyword">in</span> <span class="token punctuation">(</span>tt <span class="token punctuation">:</span><span class="token operator">=</span> tqdm<span class="token punctuation">.</span>trange<span class="token punctuation">(</span>n_epoch<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            <span class="token comment" spellcheck="true"># train</span>
            <span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>train_loader<span class="token punctuation">)</span><span class="token punctuation">:</span>
                x<span class="token punctuation">,</span> y <span class="token operator">=</span> x<span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">,</span> dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">,</span>
                                                                                          dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">)</span>
                <span class="token keyword">pass</span>

            <span class="token comment" spellcheck="true"># val</span>
            acc <span class="token operator">=</span> <span class="token number">0</span>
            all <span class="token operator">=</span> <span class="token number">0</span>
            <span class="token keyword">with</span> torch<span class="token punctuation">.</span>no_grad<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
                <span class="token keyword">for</span> step<span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">in</span> enumerate<span class="token punctuation">(</span>self<span class="token punctuation">.</span>val_loader<span class="token punctuation">)</span><span class="token punctuation">:</span>
                    x<span class="token punctuation">,</span> y <span class="token operator">=</span> x<span class="token punctuation">.</span>to<span class="token punctuation">(</span>device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">,</span> dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">)</span><span class="token punctuation">,</span> y<span class="token punctuation">.</span>to<span class="token punctuation">(</span>
                        device<span class="token operator">=</span>self<span class="token punctuation">.</span>available_device<span class="token punctuation">,</span>
                        dtype<span class="token operator">=</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>dtype<span class="token punctuation">)</span>
                    <span class="token keyword">pass</span>

                    <span class="token comment" spellcheck="true"># get acc</span>
                    acc <span class="token operator">+=</span> <span class="token punctuation">(</span>y_pred<span class="token punctuation">.</span>argmax<span class="token punctuation">(</span>dim<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">==</span> y<span class="token punctuation">.</span>squeeze<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>sum<span class="token punctuation">(</span><span class="token punctuation">)</span>
                    all <span class="token operator">+=</span> x<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
            self<span class="token punctuation">.</span>writer<span class="token punctuation">.</span>add_scalar<span class="token punctuation">(</span>tag<span class="token operator">=</span><span class="token string">"acc"</span><span class="token punctuation">,</span> scalar_value<span class="token operator">=</span><span class="token punctuation">(</span>cur_acc <span class="token punctuation">:</span><span class="token operator">=</span> acc <span class="token operator">/</span> all<span class="token punctuation">)</span><span class="token punctuation">,</span> global_step<span class="token operator">=</span>epoch<span class="token punctuation">)</span>

            <span class="token comment" spellcheck="true"># early stop</span>
            <span class="token keyword">if</span> cur_acc <span class="token operator">></span> max_acc<span class="token punctuation">:</span>
                max_acc <span class="token operator">=</span> cur_acc
                early_stop_cnt <span class="token operator">=</span> <span class="token number">0</span>
                <span class="token keyword">if</span> <span class="token operator">not</span> self<span class="token punctuation">.</span>checkpoint_path<span class="token punctuation">.</span>parent<span class="token punctuation">.</span>exists<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
                    self<span class="token punctuation">.</span>checkpoint_path<span class="token punctuation">.</span>parent<span class="token punctuation">.</span>mkdir<span class="token punctuation">(</span>parents<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
                torch<span class="token punctuation">.</span>save<span class="token punctuation">(</span>self<span class="token punctuation">.</span>network<span class="token punctuation">.</span>state_dict<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> self<span class="token punctuation">.</span>checkpoint_path<span class="token punctuation">)</span>
            <span class="token keyword">else</span><span class="token punctuation">:</span>
                early_stop_cnt <span class="token operator">+=</span> <span class="token number">1</span>

            <span class="token comment" spellcheck="true"># 注意，这里调用了tqdm的trange对象的write方法，其实别的对象也是可以的</span>
            tt<span class="token punctuation">.</span>write<span class="token punctuation">(</span>
                f<span class="token string">"Epoch [{epoch:>5d}|{n_epoch:>5d}], train_loss {train_loss:>7.4f}, val_loss {val_loss:>7.4f}, "</span>
                f<span class="token string">"early_stop_cnt: [{early_stop_cnt:>5d}|{early_stop:>5d}]"</span><span class="token punctuation">)</span>
            <span class="token keyword">if</span> early_stop_cnt <span class="token operator">>=</span> early_stop<span class="token punctuation">:</span>
                <span class="token keyword">break</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="7-网络中含有线性层的问题"><a href="#7-网络中含有线性层的问题" class="headerlink" title="7. 网络中含有线性层的问题"></a>7. 网络中含有线性层的问题</h2><p>很多时候网络中都需要写线性层，尤其是对于分类网络或者Self-Attention的结构来说。在网络中经常出现的一个情况就是前面的层不是线性层，而后面接的是线性层。这个时候就需要注意一下特征数量的问题。</p>
<p>以图像分类的卷积网络为例，输入要求的形状是：$[Batch, Channel, Width, Height]$，经过前面几个用于特征提取的层之后，feature map的形状是：$[Batch, Channel<em>{new}, Width</em>{new}, Height_{new}]$。但是对于全连接层来说，他其实干的事情就是矩阵相乘，因此要求输入的形状是$[Batch,feature_num]$。所以<strong>直接把前面层的输出丢给线性层往往是会有问题的，这个时候就需要对前面层的输出进行变换</strong>。</p>
<p>对于上面的分类的卷积网络来说，就需要把$Batch$维度之后的$Channel<em>{new}$、$Width</em>{new}$和$Height_{new}$三个维度拉平成一个向量丢给分类网络。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">forward</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> x<span class="token punctuation">:</span> torch<span class="token punctuation">.</span>Tensor<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> torch<span class="token punctuation">.</span>Tensor<span class="token punctuation">:</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>conv1<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>pool1<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>activation<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>conv2<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>pool2<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>activation<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 注意这里把后面的特征维度拉平为一个向量</span>
        x <span class="token operator">=</span> x<span class="token punctuation">.</span>flatten<span class="token punctuation">(</span>start_dim<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>linear1<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>activation<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>linear2<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>activation<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
        <span class="token keyword">return</span> self<span class="token punctuation">.</span>output<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>因此，对于不同的网络模型，在进行操作的时候一定要注意，在经过线性层之前一定要把上一层的输入处理好。</p>
<h2 id="8-TensorBoard查看多次实验"><a href="#8-TensorBoard查看多次实验" class="headerlink" title="8. TensorBoard查看多次实验"></a>8. TensorBoard查看多次实验</h2><p>TensorBoard实际上是支持一次性查看多组实验的训练过程的。多组实验的结果会显示在左下角，我们点击就可以切换</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/20180726171253594" alt="TensorBoard支持查看多组实验"></p>
<p>但是我们自己在查看的时候，很多情况下都是左下角只有一个<code>.</code>，并且只会显示一组实验的过程。</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220318160601709.png" alt="TensorBoard支持查看多组实验" style="zoom:67%;"></p>
<p>其实这是由于我们的路径选择的问题，TensorBoard会递归的扫描我们指定的目录下所有的文件，找到其中所有的event文件，然后把这个event文件所在的文件夹视为一个训练，因此我们其实只需要在启动TensorBoard的时候制定所有训练日志所在的父级目录即可，例如下面</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220318161426776.png" alt="制定打开父级文件即可"></p>
<h2 id="9-从Tensor列表中创建Tensor"><a href="#9-从Tensor列表中创建Tensor" class="headerlink" title="9. 从Tensor列表中创建Tensor"></a>9. 从Tensor列表中创建Tensor</h2><p>在Dataset读取图像的时候，进场需要进行的一个从操作就是读取图像，这个时候往往读出来的是单张图像的Tensor。我们接下来会使用一个list，来保存所有的单张图像的Tensor。在读取完接下来我们又会需要把所有的图像转换成一个大的TensorBoard，即<code>[Batch, Channel, Width, Height]</code>形状的TensorBoard。</p>
<p>这个时候我们就需要把<code>List[Tensor[Channel, Width, Height]]</code>的列表转换为<code>Tensor[Batch, Channel, Width, Height]</code>。如果直接使用<code>torch.Tensor(List[Tensor])</code>的话会报错</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220321230351403.png" alt="会抛出来ValueError"></p>
<p>这个时候我们需要用的其实是<code>torch.stack</code>，他会自动帮我们在前面构建一个维度，即</p>
<pre class="line-numbers language-python"><code class="language-python">a<span class="token punctuation">:</span> List<span class="token punctuation">[</span>torch<span class="token punctuation">.</span>Tensor<span class="token punctuation">]</span>
b <span class="token operator">=</span> torch<span class="token punctuation">.</span>stack<span class="token punctuation">(</span>a<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>其实，<code>a</code>只需要是一个以<code>torch.Tensor</code>为原子的可迭代对象即可</p>
<h2 id="10-线性层flatten问题"><a href="#10-线性层flatten问题" class="headerlink" title="10. 线性层flatten问题"></a>10. 线性层flatten问题</h2><p>前面说到，对于分类任务来说，在输入到网络进行计算的时候在线性层之前需要把输入flatten。这个时候存在一个问题，就是flatten的时候得到的feature的维度数量是和输入的时候的图像的大小是相关的。</p>
<p>因此在网络初始化的时候就需要有一个参数指定这个feature的数量。具体feature的数量完全可以单步调试的时候来确定，即</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Net</span><span class="token punctuation">(</span>nn<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> in_size<span class="token punctuation">:</span> int<span class="token punctuation">,</span> predict_class<span class="token punctuation">:</span> int<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>conv1 <span class="token operator">=</span> nn<span class="token punctuation">.</span>Sequential<span class="token punctuation">(</span>
            nn<span class="token punctuation">.</span>Conv2d<span class="token punctuation">(</span>in_channels<span class="token operator">=</span><span class="token number">3</span><span class="token punctuation">,</span> out_channels<span class="token operator">=</span><span class="token number">96</span><span class="token punctuation">,</span> kernel_size<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">,</span> stride<span class="token operator">=</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>ReLU<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>MaxPool2d<span class="token punctuation">(</span>kernel_size<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">,</span> stride<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span>
        <span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>conv2 <span class="token operator">=</span> nn<span class="token punctuation">.</span>Sequential<span class="token punctuation">(</span>
            nn<span class="token punctuation">.</span>Conv2d<span class="token punctuation">(</span>in_channels<span class="token operator">=</span><span class="token number">96</span><span class="token punctuation">,</span> out_channels<span class="token operator">=</span><span class="token number">256</span><span class="token punctuation">,</span> kernel_size<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">,</span> stride<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> padding<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>ReLU<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>MaxPool2d<span class="token punctuation">(</span>kernel_size<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">,</span> stride<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span>
        <span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 注意这里留下来了in_size</span>
        self<span class="token punctuation">.</span>linear1 <span class="token operator">=</span> nn<span class="token punctuation">.</span>Sequential<span class="token punctuation">(</span>
            nn<span class="token punctuation">.</span>Linear<span class="token punctuation">(</span>in_features<span class="token operator">=</span>in_size<span class="token punctuation">,</span> out_features<span class="token operator">=</span><span class="token number">4096</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>ReLU<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>Dropout<span class="token punctuation">(</span>p<span class="token operator">=</span><span class="token number">0.5</span><span class="token punctuation">)</span>
        <span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>linear2 <span class="token operator">=</span> nn<span class="token punctuation">.</span>Sequential<span class="token punctuation">(</span>
            nn<span class="token punctuation">.</span>Linear<span class="token punctuation">(</span>in_features<span class="token operator">=</span><span class="token number">4096</span><span class="token punctuation">,</span> out_features<span class="token operator">=</span><span class="token number">4096</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>ReLU<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            nn<span class="token punctuation">.</span>Dropout<span class="token punctuation">(</span>p<span class="token operator">=</span><span class="token number">0.5</span><span class="token punctuation">)</span>
        <span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>output <span class="token operator">=</span> nn<span class="token punctuation">.</span>Linear<span class="token punctuation">(</span>in_features<span class="token operator">=</span><span class="token number">4096</span><span class="token punctuation">,</span> out_features<span class="token operator">=</span>predict_class<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="11-持续监控GPU缓存"><a href="#11-持续监控GPU缓存" class="headerlink" title="11. 持续监控GPU缓存"></a>11. 持续监控GPU缓存</h2><p>在训练模型的时候我们需要监控内存和GPU缓存的用量。内存的用量使用htop就可以很好的来监控，但是GPU缓存的话使用<code>nvidia-smi</code>只能看到当前时刻的用量。</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220322105449663.png" alt="htop可以很好的监控系统状态，包括内存"></p>
<p>那么我们就会想问有没有类似htop、top一类可以实时监控GPU缓存用量的命令行工具呢？</p>
<p>答案其实是有的，下面几种方法都可以实现持续不断地监控GPU缓存的用量</p>
<h3 id="1-watch-nvidia-smi"><a href="#1-watch-nvidia-smi" class="headerlink" title="1. watch nvidia-smi"></a>1. watch nvidia-smi</h3><p>第一种方法就是最原始<code>watch</code>+<code>nvidia-smi</code>的方式，使用下面的命令，指定0.1秒查询一次</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">watch</span> -n0.1 nvidia-smi
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>使用效果如下</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/深度录屏_选择区域_20220322105816.gif" alt="watch+nvidia-smi的使用效果"></p>
<h3 id="2-gpustat"><a href="#2-gpustat" class="headerlink" title="2. gpustat"></a>2. gpustat</h3><p>使用<code>nvidia-smi</code>得到的输出是没有颜色的，我们就希望能不能像htop一样有彩色的输出。这个时候我们就可以结束<code>gpustat</code>这个工具实现。</p>
<p>首先安装该工具</p>
<pre class="line-numbers language-bash"><code class="language-bash">pip <span class="token function">install</span> gpustat
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>然后在安装的python环境下，使用如下命令</p>
<pre class="line-numbers language-bash"><code class="language-bash">gpustat -cp --watch
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>就可以看到如下的效果</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/深度录屏_选择区域_20220322110301.gif" alt="gpustat的效果"></p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Jack Wang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://jackwang0107.github.io/2022/02/02/shen-du-xue-xi-lian-dan-shou-ji/">https://jackwang0107.github.io/2022/02/02/shen-du-xue-xi-lian-dan-shou-ji/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Jack Wang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Python/">
                                    <span class="chip bg-color">Python</span>
                                </a>
                            
                                <a href="/tags/Deep-Learning/">
                                    <span class="chip bg-color">Deep Learning</span>
                                </a>
                            
                                <a href="/tags/Pytorch/">
                                    <span class="chip bg-color">Pytorch</span>
                                </a>
                            
                                <a href="/tags/AI/">
                                    <span class="chip bg-color">AI</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/02/02/li-hong-yi-ml2021-spring-7-convolutional-neural-network/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220202093153305.png" class="responsive-img" alt="李宏毅ML2021-Spring-7: Convolutional Neural Network (CNN)">
                        
                        <span class="card-title">李宏毅ML2021-Spring-7: Convolutional Neural Network (CNN)</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文是Machine Learning 2021 Spring 第七节课的笔记，本节课主要讲解了Neural Network架构中的Convolutional Neural Network。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-02-02
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%9D%8E%E5%AE%8F%E6%AF%85ML2021-Spring-Notes/" class="post-category">
                                    李宏毅ML2021 Spring Notes
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Deep-Learning/">
                        <span class="chip bg-color">Deep Learning</span>
                    </a>
                    
                    <a href="/tags/Hungyi-Li/">
                        <span class="chip bg-color">Hungyi Li</span>
                    </a>
                    
                    <a href="/tags/Machine-Learning/">
                        <span class="chip bg-color">Machine Learning</span>
                    </a>
                    
                    <a href="/tags/Neural-Network/">
                        <span class="chip bg-color">Neural Network</span>
                    </a>
                    
                    <a href="/tags/CNN/">
                        <span class="chip bg-color">CNN</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/01/31/latex-ji-chu-latex-zhong-de-huan-jing/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220201014340608.png" class="responsive-img" alt="Latex基础：Environments">
                        
                        <span class="card-title">Latex基础：Environments</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文主要介绍了Latex中的环境
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-01-31
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Latex%E5%9F%BA%E7%A1%80/" class="post-category">
                                    Latex基础
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Latex/">
                        <span class="chip bg-color">Latex</span>
                    </a>
                    
                    <a href="/tags/Overleaf/">
                        <span class="chip bg-color">Overleaf</span>
                    </a>
                    
                    <a href="/tags/Latex-Environment/">
                        <span class="chip bg-color">Latex Environment</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: JackWang&#39;s Blog<br />'
            + '文章作者: Jack Wang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('2'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2023</span>
            
            <a href="/about" target="_blank">Jack Wang</a>
            <!-- |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a> -->
            <!-- |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a> -->
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">603.8k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2021";
                        var startMonth = "11";
                        var startDate = "12";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
                <span id="icp"><img src="/medias/icp.png"
                                    style="vertical-align: text-bottom;"/>
                <a href="https://beian.miit.gov.cn" target="_blank">陕ICP备2021014294号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/jackwang0108" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2232123545@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2232123545" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2232123545" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
        
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/libs/others/sakura.js"><\/script>');
            }
        </script>
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
